package com.qf.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.qf.mapper.DtsCategoryMapper;
import com.qf.pojo.DtsCategory;
import com.qf.service.CateGoryService;
import com.qf.vo.CatVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class CateGoryServiceImpl implements CateGoryService {
    @Autowired
    DtsCategoryMapper categoryMapper;

    @Override
    public List<CatVo> findCategoryList() {
        //查询一级分类
        LambdaQueryWrapper<DtsCategory> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DtsCategory::getLevel, "L1");
        wrapper.eq(DtsCategory::getDeleted, false);
        //获取到了一级分类列表
        List<DtsCategory> categoryList = categoryMapper.selectList(wrapper);
        //创建返回值对象
        List<CatVo> catVoList = new ArrayList<>();
        //遍历一级分类列表
        for (DtsCategory category : categoryList) {
            //一个分类会对应一个 catVo
            CatVo catVo = new CatVo();
            //设置两个属性
            catVo.setValue(category.getId());
            catVo.setLabel(category.getName());

            //分别查询 二级分类
            LambdaQueryWrapper<DtsCategory> wrapper1 = new LambdaQueryWrapper<>();
            //指定查询是 二级分类
            wrapper1.eq(DtsCategory::getLevel, "L2");
            // 二级分类的 pid   == 一级分类的 id
            wrapper1.eq(DtsCategory::getPid, category.getId());
            //查询二级分类 列表
            List<DtsCategory> categoryListL2 = categoryMapper.selectList(wrapper1);
            //把List<DtsCategory>  转换为 List<CatVo>
            List<CatVo> catVoL2 = categoryListL2.stream().map((c) -> {
                //每一个 DtsCategory 对应一个 catVo
                CatVo catV = new CatVo();
                catV.setValue(c.getId());
                catV.setLabel(c.getName());
                return catV;
            }).collect(Collectors.toList());

            //设置  二级分类
            catVo.setChildren(catVoL2);

            catVoList.add(catVo);
        }
        return catVoList;
    }

    @Override
    public Integer findL1ById(Integer categoryL2Ids) {
        DtsCategory dtsCategory = categoryMapper.selectById(categoryL2Ids);
        return dtsCategory.getId();
    }

    @Override
    public DtsCategory selectById(Integer categoryId) {
        return categoryMapper.selectById(categoryId);
    }
}
